package Thread.day01;

/**
 * 使用同步方法解决实现Runable接口的线程安全问题
 */
public class Demo5 {
    public static void main(String[] args) {
        window4 w2 = new window4();
        Thread t1 = new Thread(w2);
        Thread t2 = new Thread(w2);
        Thread t3 = new Thread(w2);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }

}
class window4 implements Runnable{
    private  int ticket = 100;
    @Override
    public void run() {
        while(true){
                sell();
        }

    }
    //定义一个带锁的方法，此时的锁就是this：当前这个对象window4
    private synchronized void sell(){
        if (ticket>0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"卖了票号为"+ticket);
            ticket--;
        }
    }
}
